//
//  HMComposeViewController.swift
//  iOSWeibo11
//
//  Created by Apple on 16/7/27.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    /// 文字最大长度
    private let maxLength = 25
    
    /// 是否显示照片选择器的view
    private var isShowPhotoSelectorView = false

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = DefaultBKGColor
        
        setupUI()
        
        // 监听键盘的弹出和退下
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    // 移除监听
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果照片选择器没有出来才需要弹出键盘
        if !isShowPhotoSelectorView {
            // 呼出键盘
            textView.becomeFirstResponder()
        }
    }
    
    /*
    NSConcreteNotification 0x7f9a6a39cc90 {name = UIKeyboardWillChangeFrameNotification; 
        userInfo = {
            UIKeyboardAnimationCurveUserInfoKey = 7;
            UIKeyboardAnimationDurationUserInfoKey = "0.25";
            UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
            UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
            UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
            UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
            UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
            UIKeyboardIsLocalUserInfoKey = 1;
        }
    }
    */
    
    /// 键盘frame将要发生改变调用
    func willChangeFrame(notificaiton: NSNotification) {
        
        // 动画事件
        let duration: NSTimeInterval = notificaiton.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 键盘最终的位置
        let endFrame = notificaiton.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 计算toolBar的底部约束
        let bottomValue = -(UIScreen.height() - endFrame.origin.y)
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(bottomValue)
        }
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            // 强制更新view和他的子控件的frame,根据约束来更新frame
            self.view.layoutIfNeeded()
        }
    }
    
    /// 设置UI界面
    private func setupUI() {
        setupNavigationBar()
        setupTextView()
        setupPhotoSelectorView()
        setupToolBar()
        setupTipLabel()
    }
    
    /// 设置图片选择器
    private func setupPhotoSelectorView() {
        let photoSelectorView = photoSelectorVC.view
        // 添加view
        self.view.addSubview(photoSelectorView)
        
        // 当一个控制器的view成为另一个控制器的view的子view,这个控制器也需要成为另一个控制器的子view,这样事件传递才能正常,屏幕旋转才能接收到
        self.addChildViewController(photoSelectorVC)
        
        // 设置约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            let height = UIScreen.height() * 0.6
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(height)
            make.bottom.equalTo(self.view).offset(height)
        }
    }
    
    /// 设置提示label
    private func setupTipLabel() {
        // 添加控件
        self.view.addSubview(lengthTipLabel)
        
        // 添加约束
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(toolBar).offset(-3)
            make.bottom.equalTo(toolBar.snp_top).offset(-3)
        }
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加到view中
        self.view.addSubview(toolBar)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
        }
        
        // 给toolBar添加内容
        // 每个item对应的图片名称
        // 一个数组,里面的元素是字典
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_keyboardbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        toolBar.items = [UIBarButtonItem]()
        for (index, dict) in itemSettings.enumerate() {
            // 图片名称
            let imageName = dict["imageName"]!
            
            // 获取点击事件
            let action = dict["action"]!
            
            let barButtonItem = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action), tag: index)
            
            toolBar.items?.append(barButtonItem)
            
            // 弹簧
            let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            toolBar.items?.append(flexible)
        }
        
        // 删除最后一个弹簧
        toolBar.items?.removeLast()
    }
    
    // MARK: - 按钮点击事件
    @objc private func picture() {
        // 弹出照片选择view
        photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(0)
        }
        
        UIView.animateWithDuration(DefaultAnimtionDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        // 退回键盘
        self.textView.resignFirstResponder()
        
        isShowPhotoSelectorView = true
    }
    
    @objc private func trend() {
        print("#")
    }
    
    @objc private func mention() {
        print("@")
    }
    
    @objc private func emoticon(button: UIButton) {
        // 切换表情
        // 设置inputView并不会立马切换键盘, 在弹出键盘那一刻,如果不设置inputView 弹出的是系统键盘,如果设置了intputView就弹设置的view
        // 先让键盘回去
        textView.resignFirstResponder()
        
        // 再设置自定义键盘
        let inputView: UIView? = textView.inputView == nil ? emoticonKeyboard : nil
        textView.inputView = inputView
        
        // 设置点击按钮的图片
        var image: String
        if inputView == nil {
            image = "compose_keyboardbutton_background"
        } else {
            image = "compose_emoticonbutton_background"
        }
        button.setImage(UIImage(named: image), forState: UIControlState.Normal)
        button.setImage(UIImage(named: image + "_highlighted"), forState: UIControlState.Highlighted)
        
        // 延迟0.25秒弹出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 再弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    @objc private func add() {
        print("+")
    }
    
//    @objc private func buttonItemClick(button: UIButton) {
//        switch button.tag {
//        case 0:
//            print("图片")
//        case 1:
//            print("#")
//        case 2:
//            print("@")
//        case 3:
//            print("表情")
//        case 4:
//            print("+")
//        default:
//            print("没有这个按钮")
//        }
//    }
    
    /// 设置textView
    private func setupTextView() {
        // 添加控件
        self.view.addSubview(textView)
        
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        // 右边按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitle()
    }
    
    /// 设置title
    private func setupTitle() {
        let prefix = "发微博"
        
        // 获取用户名称
        if let  screen_name = HMUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name {
            // 有用户名称
            // \n 换行
            let content = prefix + "\n" + screen_name
            
            let titleLabel = UILabel()
            
            titleLabel.font = UIFont.systemFontOfSize(14)
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            
            // 属性文本,可以任何字符设置属性
            let attrText = NSMutableAttributedString(string: content)
            
            // 选中要修改属性的文字,设置属性
            let range = (content as NSString).rangeOfString(screen_name)
            
            // 一次添加一个属性
//            attrText.addAttribute(<#T##name: String##String#>, value: <#T##AnyObject#>, range: <#T##NSRange#>)
            
            // 一次添加多个属性
            attrText.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: range)
            
            // 设置属性文本给label
            titleLabel.attributedText = attrText
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
            
        } else {
            // 没有用户名称
            navigationItem.title = prefix
        }
    }
    
    /// 关闭控制器
    @objc private func close() {
        SVProgressHUD.dismiss()
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        // 获取要发布的文字
        let text = textView.emoticonText()
        
        // 判断是否超出长度
        if text.characters.count > maxLength {
            SVProgressHUD.showErrorWithStatus("文字超出长度了...")
            return
        }
        
        // 获取要发送的图片, 数组的第一张
        let sendImage = photoSelectorVC.photos.first
        
        // 没有超出长度, 发布微博
        SVProgressHUD.showWithStatus("正在发布微博...")
        HMStatusViewModel.sharedStatusViewModel.sendStatus(text, image: sendImage) { (error) -> Void in
            if error != nil {
                print("error: \(error)")
                
                SVProgressHUD.showErrorWithStatus("发布微博失败了")
                
                return
            }
            
            // 发布微博成功了
            SVProgressHUD.showSuccessWithStatus("发布微博成功了")
            // 延时关闭
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
    }

    // MARK: - 懒加载
    /*
        iOS中可以输入的控件
            1.UITextField
                1.只能输入一行
                2.有占位文本
                3.不能滚动
    
            2.UITextView
                1.可以输入多行
                2.没有占位文本
                3.可以滚动
    */
    
    /// 自定义一个带占位文本的textView
    private lazy var textView: HMPlaceholerTextView = {
        let tv = HMPlaceholerTextView()
        
        // 设置文字大小
        tv.font = UIFont.systemFontOfSize(18)
        // 垂直方向一直有弹簧效果
        tv.alwaysBounceVertical = true
        // 当拖动的时候就会自己关闭
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 监听textView文字的改变
        tv.delegate = self
        
        // 尽量不要把控件暴露给别人
//        tv.placeholderLabel.text = "请输入微博内容..."
//        tv.placeholderLabel.frame = CGRectZero
//        tv.placeholderLabel.removeFromSuperview()
        
        tv.placehodler = "请输入微博内容..."
        
        return tv
    }()
    
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    /// 自定义的表情键盘的view
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    /// 长度提示label
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 11)
        
        label.text = "\(self.maxLength)"
        
        return label;
    }()
    
    /// 图片选择控制器
    private lazy var photoSelectorVC: HMPhotoSelectorViewController = HMPhotoSelectorViewController()
}

extension HMComposeViewController: UITextViewDelegate {
    /// 文字改变了
    func textViewDidChange(textView: UITextView) {
        // 有文字可用,没文字不可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 获取输入的数量
        let inputCount = textView.emoticonText().characters.count
        
        // 设置剩余的长度
        lengthTipLabel.text = "\(maxLength - inputCount)"
        
        // 如果超出了长度,文字改为红色
        if inputCount > maxLength {
            lengthTipLabel.textColor = UIColor.redColor()
        } else {
            lengthTipLabel.textColor = UIColor.lightGrayColor()
        }
    }
}
